package com.yuan.security.aspect;


import cn.common.constant.CacheConstant;
import cn.common.constant.TokenConstants;
import cn.common.exception.BusinessException;
import cn.common.exception.TokenException;
import cn.common.utils.JwtUtils;
import cn.common.utils.StringUtils;
import cn.common.utils.UserContextUtils;
import com.yuan.common.redis.service.RedisRepository;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

@Slf4j
@Component
@Aspect
public class LoginAspect {
    @Autowired
    private RedisRepository redisRepository;
    @Pointcut("@annotation(com.yuan.security.annotation.RequiresLogin)")
    public void loginCheckPointCut() {}

    @Before("loginCheckPointCut()")
    public void checkLogin(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(
                RequestContextHolder.getRequestAttributes())).getRequest();
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isBlank(authorization)) {
            throw new TokenException("不是有效用户");
        }
        String token =  authorization.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
        if (authorization.isEmpty() || !validateToken(token)) {
            throw new TokenException("用户未登录或令牌无效");
        }
    }

    private boolean validateToken(String token) {
        String user = "";
        try {
            // 解析 JWT 逻辑（示例）
             user =  JwtUtils.getUsernameFromToken(token);
        } catch (MalformedJwtException e) {
            throw new TokenException("token获取异常");
        }catch (ExpiredJwtException e) {
            throw new TokenException("tokens已过期");
        }
        //判断传入的token是否和redis一样
        String auth_token =  redisRepository.get(CacheConstant.LOGIN_TOKEN_KEY + user);
         if(!Objects.equals(auth_token, token)){
             throw new TokenException("用户已过期或者其它地方已登录");
         }
        UserContextUtils.setCurrentUserId(user);
        return JwtUtils.validateToken(token);
        // 使用 jjwt 解析令牌
       // return token.startsWith("Bearer  valid_"); // 替换为真实解析逻辑
    }
}
